package com.campus.common.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * <pre>
 * 集合分批迭代
 * </pre>
 */
public class BatchIteratorUtil<E> implements Iterator<List<E>> {
    /**
     * 当前的批次集合返回的元素个数
     */
    private int batchSize;
    private List<E> srcList;
    private int index = 0;
    private List<E> result;
    private int size = 0;

    public BatchIteratorUtil(List<E> srcList, int batchSize) {
        if (0 >= batchSize) {
            throw new RuntimeException(
                    "Please do not be set less than or equal to '0' for batchSize !");
        }
        this.batchSize = batchSize;
        this.srcList = srcList;
        this.size = null == srcList ? 0 : srcList.size();
        result = new ArrayList<E>(batchSize);
    }
    @Override
    public boolean hasNext() {
        return index < size;
    }
    @Override
    public List<E> next() {
        result.clear();
        for (int i = 0; i < batchSize && index < size; i++) {
            result.add(srcList.get(index++));
        }
        return result;
    }

    // 测试代码已移除，如需测试请在单元测试中进行

}